package com.baoli.blzj.ui.fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.baoli.blzj.adapter.home.HomeGnAdapter;
import com.baoli.blzj.bean.home.HomePagerAdvertBean;
import com.baoli.blzj.bean.home.HomeRollBean;
import com.baoli.blzj.bean.home.HomeTotalListBean;
import com.baoli.blzj.customviews.CustomToast;
import com.baoli.blzj.customviews.RollADTextView;
import com.baoli.blzj.ui.common.PublicWebActivity;
import com.baoli.blzj.utils.CancelPublicUtil;
import com.baoli.blzj.utils.CustomCalcHeightUtils;
import com.baoli.blzj.utils.HomeDataJieXiUtils;
import com.baoli.blzj.utils.SizeUtil;
import com.bumptech.glide.Glide;
import com.jude.rollviewpager.RollPagerView;
import com.baoli.blzj.Constants;
import com.baoli.blzj.R;
import com.baoli.blzj.adapter.home.HomeAdapter;
import com.baoli.blzj.adapter.home.HomeRollAdapter;
import com.baoli.blzj.adapter.home.HomeRollMeunAdapter;
import com.baoli.blzj.bean.home.HomeMenuBean;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.cache.CacheMode;
import com.lzy.okhttputils.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

import static android.content.Context.MODE_PRIVATE;

/**
 * 首页Fragment by john
 */

public class HomeFragment extends BaseFragment implements OnRefreshListener, OnLoadMoreListener, Constants {

    private SharedPreferences spn;

    private SharedPreferences.Editor editor;

    private SwipeToLoadLayout swipeToLoadLayout;

    private ListView listView;

    private LinearLayout addLayout;

    private RelativeLayout lb_layout, gun_layout;

    private RollPagerView rollPagerViews, menu_grid, gg_viewpager;

    private HomeRollAdapter madapter, gadapter;//轮播图适配器

    private LinearLayout mADTextView;//滚动通知视图

    private HomeRollMeunAdapter medapter;//菜单按钮适配器

    private List<HomePagerAdvertBean> img_list;//轮播图集合

    private List<HomeMenuBean> menuList;//按钮集合

    private List<List<HomeMenuBean>> views;//菜单按钮集合

    private List<HomeRollBean> aList;//滚动通知集合

    private List<HomeTotalListBean> totalList, allList;

    private HomeMenuBean totalBean;//热门推荐

    private boolean tzLayout = false;//滚动通知是否展示

    private HomeAdapter hAdapter;

    private int screenWidth, p = 1;

    private String phone = "";

    public static HomeFragment newInstance() {
        HomeFragment fragment = new HomeFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        spn = getActivity().getSharedPreferences(SPN_BLZJ, MODE_PRIVATE);
        editor = spn.edit();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.home_activity_list, container, false);
        swipeToLoadLayout = (SwipeToLoadLayout) view.findViewById(R.id.swipeToLoadLayout);
        listView = (ListView) view.findViewById(R.id.swipe_target);
        addLayout = (LinearLayout) inflater.inflate(R.layout.home_activity_add, null);
        setLunBo();
        hAdapter = new HomeAdapter(getActivity());
        listView.addHeaderView(addLayout);
        listView.setAdapter(hAdapter);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        swipeToLoadLayout.setOnRefreshListener(this);
        swipeToLoadLayout.setOnLoadMoreListener(this);
        swipeToLoadLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeToLoadLayout.setRefreshing(true);
            }
        });
    }

    @Override
    public void onLoadMore() {
        p++;
        //httpRequest(1, HTTP_MAIN + "?sqid=" + AESEncryptor.decrypt(spn.getString(SPN_SQID, "")) + "&uid=" + AESEncryptor.decrypt(spn.getString(SPN_UID, "")) + "&p=" + p + "&count=20");
        httpRequest(1, "http://tsq.test.xiaohesoft.com/platformapi/sqapi/gbcomity_main.php?sqid=2&uid=1&p=" + p + "&count=20");
    }

    @Override
    public void onRefresh() {
        p = 1;
        //httpRequest(0, HTTP_MAIN + "?sqid=" + AESEncryptor.decrypt(spn.getString(SPN_SQID, "")) + "&uid=" + AESEncryptor.decrypt(spn.getString(SPN_UID, "")) + "&p=" + p + "&count=20");
        httpRequest(0, "http://tsq.test.xiaohesoft.com/platformapi/sqapi/gbcomity_main.php?sqid=2&uid=1&p=1&count=20");
    }

    /**
     * 初始化轮播图
     */
    private void setLunBo() {
        //轮播图
        rollPagerViews = (RollPagerView) addLayout.findViewById(R.id.main_rollviewpager);
        CustomCalcHeightUtils.getInstance().setHeight(rollPagerViews, getActivity(), 5).setAnimationDurtion(500);
        madapter = new HomeRollAdapter(getActivity());
        madapter.setfrom(1);
        rollPagerViews.setAdapter(madapter);
        setViewAdapter();
        //广告轮播
        gg_viewpager = (RollPagerView) addLayout.findViewById(R.id.gg_viewpager);
        CustomCalcHeightUtils.getInstance().setHeight(gg_viewpager, getActivity(), 3).setAnimationDurtion(500);
        gadapter = new HomeRollAdapter(getActivity());
        gadapter.setfrom(1);
        gg_viewpager.setAdapter(gadapter);
        gun_layout = (RelativeLayout) addLayout.findViewById(R.id.gun_layout);
        mADTextView = (LinearLayout) addLayout.findViewById(R.id.ad_textview);
    }

    /**
     * 初始化滚动通知
     */
    private void setGunList() {
        if (tzLayout) {
            gun_layout.setVisibility(View.VISIBLE);
            RollADTextView ad = new RollADTextView(getActivity());
            mADTextView.removeAllViews();
            ad.setSpeed(3);
            ad.setTexts(aList);
            if (aList.size() == 1) {
                ad.setInterval(200000);
            } else {
                ad.setInterval(2000);
            }
            ad.setOnItemClickListener(new RollADTextView.OnItemClickListener() {
                @Override
                public void onClick(String mUrl, String name) {
                    Intent intent = new Intent(getActivity(), PublicWebActivity.class);
                    intent.putExtra("url", mUrl);
                    intent.putExtra("name", "热门通知");
                    startActivity(intent);
                }
            });
            mADTextView.addView(ad);
        } else {
            gun_layout.setVisibility(View.GONE);
            mADTextView.setVisibility(View.GONE);
        }
    }

    /**
     * 初始化菜单
     */
    private void setInitMenu() {

        medapter.notifyDataSetChanged();
        views = new ArrayList<>();
        if (menuList.size() > 0) {
            if (menuList.size() < 10) {
                views.add(menuList.subList(0, menuList.size()));
            } else {
                if (menuList.size() % 10 == 0) {//如果功能数量是10的倍数
                    int num = menuList.size() / 10;//那么就创建这个倍数的页面
                    for (int i = 0; i < num; i++) {
                        views.add(menuList.subList(i * 10, i * 10 + 10));
                    }
                } else {
                    int num = menuList.size() / 10;//如果功能数量不是10的倍数,那么余下的数量也需要对创建一个页面
                    for (int i = 0; i < num; i++) {
                        views.add(menuList.subList(i * 10, i * 10 + 10));
                    }
                    views.add(menuList.subList(num * 10, menuList.size()));
                }
            }
        }
        menu_grid.setAdapter(medapter);
        if (views.size() <= 10) {//如果功能分类小于10个也就是一个页那么隐藏圆点视图
            menu_grid.setHintIsShow(true);
            CustomCalcHeightUtils.getInstance().setHeight(lb_layout, getActivity(), SizeUtil.Dp2Px(getActivity(), 170));
        } else {//否则放开
            menu_grid.setHintIsShow(false);
            CustomCalcHeightUtils.getInstance().setHeight(lb_layout, getActivity(), SizeUtil.Dp2Px(getActivity(), 190));
        }
        medapter.setList(views);
        menu_grid.getViewPager().setCurrentItem(0);
    }

    /**
     * 初始化菜单按钮分页适配器
     */
    private void setViewAdapter() {
        lb_layout = (RelativeLayout) addLayout.findViewById(R.id.viewpager);
        CustomCalcHeightUtils.getInstance().setHeight(lb_layout, getActivity(), SizeUtil.Dp2Px(getActivity(), 170));
        menu_grid = (RollPagerView) addLayout.findViewById(R.id.menu_grid);
        medapter = new HomeRollMeunAdapter(getActivity());
    }


    /**
     * 网络请求
     */
    private void httpRequest(final int tag, String url) {

        img_list = new ArrayList<>();
        menuList = new ArrayList<>();
        aList = new ArrayList<>();
        totalList = new ArrayList<>();
        allList = new ArrayList<>();
        totalList = new ArrayList<>();
        totalBean = new HomeMenuBean();

        OkHttpUtils.get(url)
                .tag(this)
                .cacheMode(CacheMode.DEFAULT)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response responseResult) {
                        try {
                            JSONObject response = new JSONObject(s);
                            String recode, msg;
                            recode = response.getString("recode");
                            msg = response.getString("msg");
                            if (recode.equals("0")) {
                                if (response.has("img_list")) {
                                    img_list = HomeDataJieXiUtils.getInstance().getImgDatas(img_list, response.getJSONArray("img_list"));
                                }
                                if (response.has("gn_list")) {
                                    menuList = HomeDataJieXiUtils.getInstance().getMenuDatas(menuList, response.getJSONArray("gn_list"));
                                }
                                if (response.has("wuye_list")) {
                                    JSONArray tzArr = response.getJSONArray("wuye_list");
                                    if (tzArr.length() == 0) {
                                        tzLayout = false;
                                    } else {
                                        for (int i = 0; i < tzArr.length(); i++) {
                                            JSONObject tzObj = tzArr.getJSONObject(i);
                                            String news = tzObj.getString("title");
                                            if (news.length() > 16) {
                                                news = news.substring(0, 15) + "...";
                                            }
                                            aList.add(new HomeRollBean(news, "", tzObj.getString("url")));
                                        }
                                        tzLayout = true;
                                    }
                                }
                                if (response.has("hot_list")) {
                                    JSONObject bean = response.getJSONObject("hot_list");
                                    totalBean.setFun_name(bean.getString("title"));
                                    totalBean.setFuc_url(bean.getString("url"));
                                    totalBean.setFuc_classname(bean.getString("time"));
                                    totalBean.setFuc_img(bean.getString("img"));
                                    totalBean.setFuncType(bean.getString("islogin"));
                                }
                                if (response.has("rm_list")) {
                                    totalList = HomeDataJieXiUtils.getInstance().getTotalDatas(totalList, response.getJSONArray("rm_list"));
                                }
                                handler.sendEmptyMessage(tag);

                            } else if (recode.equals("111111")) {
                                swipeToLoadLayout.setRefreshing(false);
                                swipeToLoadLayout.setLoadingMore(false);
                                CancelPublicUtil.getInstance().deleteData(getActivity(), msg);
                            } else {
                                swipeToLoadLayout.setRefreshing(false);
                                swipeToLoadLayout.setLoadingMore(false);
                                CustomToast.showToast(getActivity(), msg, 1000);
                            }
                        } catch (Exception e) {
                            swipeToLoadLayout.setRefreshing(false);
                            swipeToLoadLayout.setLoadingMore(false);
                            CustomToast.showToast(getActivity(), R.string.http_fail, 1000);
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        CustomToast.showToast(getActivity(), R.string.http_fail, 1000);
                    }
                });
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(final Message msg) {
            switch (msg.what) {
                case 0:
                    allList = new ArrayList<>();
                    allList.addAll(totalList);
                    swipeToLoadLayout.setRefreshing(false);
                    hAdapter.setList(allList);
                    setData();
                    break;
                case 1:
                    swipeToLoadLayout.setLoadingMore(false);
                    allList.addAll(totalList);
                    hAdapter.append(totalList);
                    break;
            }
        }
    };

    /**
     * 数据处理
     */
    public void setData() {
        try {
            /**
             * 初始化轮播图
             */
            madapter.setList(img_list);

            setInitMenu();

            setGunList();

            /**
             * 初始化广告轮播图
             */
            gadapter.setList(img_list);

            hAdapter.setList(allList);
        } catch (Exception e) {
        }
    }

   /* private void httpGetKeFu(String url) {

        JsonObjectHeadersPostRequest request = new JsonObjectHeadersPostRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                String recode, msg;
                try {
                    if (response.has("recode")) {
                        recode = response.getString("recode");
                        msg = response.getString("msg");
                        if (recode.equals("0")) {
                            if (response.has("phone")) {
                                phone = response.getString("phone");
                            }
                            handler.sendEmptyMessage(1);
                        } else if (recode.equals("111111")) {
                            CancelPublicActivity.getInstance().deleteData(getActivity(), msg);
                        } else {
                            CustomToast.showToast(getActivity(), msg, 1000);
                        }
                    }
                } catch (Exception e) {
                    CustomToast.showToast(getActivity(), R.string.http_fail, 1000);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                CustomToast.showToast(getActivity(), R.string.http_fail, 1000);
            }
        });
        queue.add(request);
    }*/

    /**
     * 功能菜单点击事件
     */
    /*public void setOnClicks(List<HomeMenuBean> menuList, int position) {

        if ("1".equals(menuList.get(position).getFuc_type())) {
            if ("1".equals(menuList.get(position).getFuncType())) {
                if ("wyjf".equals(menuList.get(position).getFuc_classname())) {

                    if (spn.getBoolean(SPN_IS_LOGIN, false)) {
                        if (spn.getString(SPN_SQID, "").equals("")) {
                            CustomToast.showToast(getActivity(), "请选择小区", 1000);
                        } else {
                            Intent intent = new Intent();
                            intent.setClass(getActivity(), HomeWyfwjfActivity.class);
                            getActivity().startActivity(intent);
                        }
                    } else {
                        Intent intent = new Intent();
                        intent.setClass(getActivity(), PersonalLoginActivity.class);
                        getActivity().startActivityForResult(intent, 101);
                    }
                } else if ("wykf".equals(menuList.get(position).getFuc_classname())) {
                    httpGetKeFu(HTTP_ONLINE_SERVICE);
                } else if ("jshs".equals(menuList.get(position).getFuc_classname())) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), HomeBodyBuildingActivity.class);
                    getActivity().startActivity(intent);

                } else if ("dcxs".equals(menuList.get(position).getFuc_classname())) {
                    Intent intent = new Intent(getActivity(), HomeLandListActivity.class);
                    intent.putExtra("name", menuList.get(position).getFun_name());
                    getActivity().startActivity(intent);
                } else if ("wybx".equals(menuList.get(position).getFuc_classname())) {
                    if (spn.getBoolean(SPN_IS_LOGIN, false)) {
                        if (spn.getString(SPN_SQID, "").equals("")) {
                            CustomToast.showToast(getActivity(), "请选择小区", 1000);
                        } else {
                            Intent intent = new Intent();
                            intent.setClass(getActivity(), HomeRepairOrderListActivity.class);
                            getActivity().startActivity(intent);
                        }
                    } else {
                        Intent intent = new Intent();
                        intent.setClass(getActivity(), PersonalLoginActivity.class);
                        getActivity().startActivityForResult(intent, 101);
                    }

                } else if ("wytz".equals(menuList.get(position).getFuc_classname())) {
                    if (spn.getBoolean(SPN_IS_LOGIN, false)) {
                        if (spn.getString(SPN_SQID, "").equals("")) {
                            CustomToast.showToast(getActivity(), "请选择小区", 1000);
                        } else {
                            Intent intent = new Intent();
                            intent.setClass(getActivity(), HomePropertyNoticeActivity.class);
                            getActivity().startActivity(intent);
                        }
                    } else {
                        Intent intent = new Intent();
                        intent.setClass(getActivity(), PersonalLoginActivity.class);
                        getActivity().startActivityForResult(intent, 101);
                    }
                } else if ("sxts".equals(menuList.get(position).getFuc_classname())) {
                    if (spn.getBoolean(SPN_IS_LOGIN, false)) {
                        if (spn.getString(SPN_SQID, "").equals("")) {
                            CustomToast.showToast(getActivity(), "请选择小区", 1000);
                        } else {
                            Intent intent = new Intent();
                            intent.setClass(getActivity(), HomeThingComplainActivity.class);
                            getActivity().startActivity(intent);
                        }
                    } else {
                        Intent intent = new Intent();
                        intent.setClass(getActivity(), PersonalLoginActivity.class);
                        getActivity().startActivityForResult(intent, 101);
                    }

                } else if ("gjfw".equals(menuList.get(position).getFuc_classname())) {
                    if (spn.getBoolean(SPN_IS_LOGIN, false)) {
                        if (spn.getString(SPN_SQID, "").equals("")) {
                            CustomToast.showToast(getActivity(), "请选择小区", 1000);
                        } else {
                            Intent intent = new Intent();
                            intent.setClass(getActivity(), HomeAuthAddressListActivity.class);
                            getActivity().startActivity(intent);
                        }
                    } else {
                        Intent intent = new Intent();
                        intent.setClass(getActivity(), PersonalLoginActivity.class);
                        getActivity().startActivityForResult(intent, 101);
                    }
                } else if ("jrfw".equals(menuList.get(position).getFuc_classname())) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), HomeJrfwActivity.class);
                    getActivity().startActivity(intent);
                } else if ("jtyl".equals(menuList.get(position).getFuc_classname())) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), HomeYlActivity.class);
                    getActivity().startActivity(intent);
                } else if ("swfw".equals(menuList.get(position).getFuc_classname())) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), CommunitySwInfoActivity.class);
                    getActivity().startActivity(intent);
                } else if ("smfw".equals(menuList.get(position).getFuc_classname())) {
                    ((MainActivity) getActivity()).viewPager.setCurrentItem(1);
                } else if ("shjf".equals(menuList.get(position).getFuc_classname())) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), HomeLifeJfActivity.class);
                    getActivity().startActivity(intent);
                } else if ("wyfw".equals(menuList.get(position).getFuc_classname())) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), HomePropertyServiceActivity.class);
                    getActivity().startActivity(intent);
                } else if ("ylfw".equals(menuList.get(position).getFuc_classname())) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), HomeYlFwActivity.class);
                    getActivity().startActivity(intent);
                } else if ("dcjs".equals(menuList.get(position).getFuc_classname())) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), HomeLandListActivity.class);
                    getActivity().startActivity(intent);
                } else if ("jkda".equals(menuList.get(position).getFuc_classname())) {
                    if (spn.getBoolean(SPN_IS_LOGIN, false)) {
                        Intent intentscdd = new Intent(getActivity(), PersonalHealthActivity.class);
                        intentscdd.putExtra("tag", "2");
                        getActivity().startActivity(intentscdd);
                    } else {
                        Intent intent = new Intent();
                        intent.setClass(getActivity(), PersonalLoginActivity.class);
                        getActivity().startActivityForResult(intent, 101);
                    }
                } else if ("yygh".equals(menuList.get(position).getFuc_classname())) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), HomeLifeDetailActivity.class);
                    intent.putExtra("tag", "lc");
                    getActivity().startActivity(intent);
                } else if ("bgcx".equals(menuList.get(position).getFuc_classname())) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), HomeLifeDetailActivity.class);
                    intent.putExtra("tag", "lc");
                    getActivity().startActivity(intent);
                } else if ("zls".equals(menuList.get(position).getFuc_classname())) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), HomeLifeDetailActivity.class);
                    intent.putExtra("tag", "sf");
                    getActivity().startActivity(intent);
                } else if ("lcbx".equals(menuList.get(position).getFuc_classname())) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), HomeSearchProjectActivity.class);
                    intent.putExtra("func_id", menuList.get(position).getMessType());
                    intent.putExtra("name", menuList.get(position).getFun_name());
                    getActivity().startActivity(intent);
                }

            } else if ("2".equals(menuList.get(position).getFuncType())) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), HomeSearchProjectActivity.class);
                intent.putExtra("func_id", menuList.get(position).getFun_cid());
                intent.putExtra("name", menuList.get(position).getFun_name());
                getActivity().startActivity(intent);

            } else if ("3".equals(menuList.get(position).getFuncType())) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), PublicHaveTitleWebActivity.class);
                intent.putExtra("url", menuList.get(position).getFuc_url());
                intent.putExtra("name", menuList.get(position).getFun_name());
                getActivity().startActivity(intent);
            } else if ("4".equals(menuList.get(position).getFuncType())) {
                Intent intent = new Intent(getActivity(), CommunitySupermarketListActivity.class);
                intent.putExtra("func_id", menuList.get(position).getFun_cid());
                intent.putExtra("type", "sm");
                intent.putExtra("name", menuList.get(position).getFun_name());
                getActivity().startActivity(intent);
            }
        } else if ("2".equals(menuList.get(position).getFuc_type())) {

        }
    }*/
}